import React, { Component } from 'react';
import { View, Image, ScrollView, Text, TouchableOpacity, FlatList, RefreshControl } from 'react-native';
import Colors from '../constants/Colors';
import { MyHeader } from '../components/MyHeader';
import { unitWidth, width, height } from '../constants/AdapterUtil';
import MyListView from '../components/MyListView';
import ScrollableTabView, { ScrollableTabBar, DefaultTabBar } from 'react-native-scrollable-tab-view';
import { DeleteTextView } from '../components/MyTextView';
import EmptyView from '../components/EmptyView';
import RefreshFooter from '../components/RefreshFooter';
import Swiper from 'react-native-swiper';
import { SubmitButton4, SubmitButton5, SMButton, SDButton, AddShoppingCartButton } from '../components/Button';
import NavigationService from '../constants/NavigationService';
import { api_goods_detail, api_goods_get_list, api_member_cart_add } from '../constants/HttpServices';
import { postFetch } from '../constants/HttpExtension';
import { WebView } from 'react-native-webview';
import CommonUtil from '../constants/CommonUtil';
import { show } from '../constants/Toast';
import { BottomCountModal } from '../components/Modal';

export default class GoodsDetailScreen extends Component {
    constructor(props) {
        super(props)
        this.id = this.props.navigation.getParam('id', 0);
        this.state = {
            CarouselList: [

            ],

            currentChoose: 0,
            height: 500 * unitWidth,
            refreshing: false,
            goodsInfo: {},
            shopInfo: {},

            htmlHeight: 0
        }
    }

    componentDidMount() {
        this.props.navigation.addListener('didFocus', payload => {
            this.state.currentChoose == 0 ? this.refs.screen1.measure() : this.refs.screen2.measure();
            this.getData();
        })
    }

    render() {
        return (
            <View style={{ flex: 1, backgroundColor: Colors.colorF7 }}>
                <MyHeader title='商品详情' leftImg={require('../res/ic_arrow_left.png')} leftClick={() => { this.props.navigation.pop() }} />
                <ScrollView style={{ marginBottom: 50 * unitWidth }}
                    showsVerticalScrollIndicator={false}
                    refreshControl={
                        <RefreshControl
                            refreshing={this.state.refreshing}
                            onRefresh={this.onRefresh.bind(this)}
                            colors={[Colors.headerColor]}
                            progressBackgroundColor="#ffffff"
                        />
                    }
                    onMomentumScrollEnd={(event) => {
                        const contentHeight = event.nativeEvent.contentSize.height;
                        const scrollViewHeight = event.nativeEvent.layoutMeasurement.height;
                        const scrollOffset = event.nativeEvent.contentOffset.y;

                        const isEndReached = scrollOffset + scrollViewHeight >= contentHeight - (10 * unitWidth); // 是否滑动到底部
                        const isContentFillPage = contentHeight >= scrollViewHeight; // 内容高度是否大于列表高度
                        if (isContentFillPage && isEndReached) {
                            this.onLoadMore();
                        }
                    }} >
                    <View>
                        <View style={{ alignItems: 'center' }}>
                            {
                                this.state.CarouselList && this.state.CarouselList.length > 0 ?
                                    <View style={{ width: width, height: 225 * unitWidth }}>
                                        <Swiper style={{ width: width, height: 225 * unitWidth }} loop={true} autoplay={true} dotStyle={{ marginBottom: -20 * unitWidth }} activeDotStyle={{ marginBottom: -20 * unitWidth }}>
                                            {this.getCarouselView()}
                                        </Swiper>
                                    </View> : null
                            }
                            <View style={{ paddingHorizontal: 20 * unitWidth, width: width, backgroundColor: Colors.white }}>
                                <View style={{ marginTop: 10 * unitWidth, flexDirection: 'row', alignItems: 'flex-end', alignSelf: 'flex-start' }}>
                                    <Text style={{ color: Colors.colorRed, fontSize: 17, }}>￥{this.state.goodsInfo.marketprice}</Text>
                                    <DeleteTextView text={'￥' + this.state.goodsInfo.productprice} style={{ marginLeft: 5 * unitWidth }} />
                                </View>
                                <View style={{ flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', marginTop: 5 * unitWidth }}>
                                    <View style={{
                                        paddingHorizontal: 7 * unitWidth, borderWidth: 0.5,
                                        borderColor: Colors.colorRed, borderRadius: 5, alignSelf: 'flex-start'
                                    }}>
                                        <Text style={{ color: Colors.colorRed, fontSize: 11, }}>线下价格:￥{this.state.goodsInfo.offlineprice}</Text>
                                    </View>
                                    <Text style={{ color: Colors.colorOrange, fontSize: 13, }}>数量：{this.state.goodsInfo.total}</Text>
                                </View>
                                <Text style={{ color: Colors.black, fontSize: 15, marginTop: 5 * unitWidth }}>{this.state.goodsInfo.title}</Text>
                            </View>
                            <Image source={require('../res/spxq_fxgfw.png')}
                                style={{ width: width, height: 50 * unitWidth }}
                                resizeMode='stretch' />
                            <TouchableOpacity style={{
                                width: width, height: 70 * unitWidth, alignItems: 'center', flexDirection: 'row', paddingHorizontal: 20 * unitWidth,
                                backgroundColor: Colors.white, marginVertical: 5 * unitWidth
                            }} activeOpacity={0.7} onPress={() => {
                                this.props.navigation.navigate('ServiceProviderDetail', { merchid: this.state.goodsInfo.merchid })
                            }}>
                                <Image source={{ uri: this.state.shopInfo.logo }}
                                    style={{ width: 50 * unitWidth, height: 50 * unitWidth, borderRadius: 25 * unitWidth }}
                                    resizeMode='cover' />
                                <View style={{ marginLeft: 10 * unitWidth, width: width }}>
                                    <Text style={{ color: Colors.color33, fontSize: 15, }}>{this.state.shopInfo.shopname}</Text>
                                    <View style={{ flexDirection: 'row', alignItems: 'center', marginTop: 7 * unitWidth }}>
                                        {this.state.shopInfo.is_realname > 0 ? <SMButton id={this.state.goodsInfo.merchid} /> : null}
                                        {this.state.shopInfo.is_realname > 2 ? <SDButton style={{ marginLeft: 5 * unitWidth }} id={this.state.goodsInfo.merchid} /> : null}
                                    </View>
                                </View>
                                <View style={{ flexDirection: 'row', alignItems: 'center', right: 20 * unitWidth, position: 'absolute' }}>
                                    <Text style={{ color: Colors.colorRed, fontSize: 14 }}>进入店铺</Text>
                                    <Image source={require('../res/spxq_jrdpback.png')}
                                        style={{ width: 7 * unitWidth, height: 14 * unitWidth }}
                                        resizeMode='stretch' />
                                </View>
                            </TouchableOpacity>
                        </View>
                        <ScrollableTabView
                            style={{ height: this.state.height }}
                            tabBarUnderlineStyle={{ backgroundColor: Colors.transparent }}
                            tabBarActiveTextColor={Colors.colorRed}
                            tabBarInactiveTextColor={Colors.color99}
                            initialPage={0}
                            onChangeTab={(value) => {
                                this.setState({
                                    currentChoose: value.i
                                })
                                if (value.i == 0) {
                                    if (this.state.htmlHeight != 0) {
                                        this.refs.screen1.measure(this.state.htmlHeight);
                                    } else {
                                        this.refs.screen1.measure();
                                    }
                                } else {
                                    this.refs.screen2.measure();
                                }
                            }}
                            renderTabBar={() => <DefaultTabBar style={{
                                height: 50,
                                borderColor: Colors.transparent,
                            }} renderTab={
                                (name, page, isTabActive, onPressHandler, onLayoutHandler) => {
                                    const { activeTextColor, inactiveTextColor, textStyle, } = this.props;
                                    const textColor = isTabActive ? Colors.colorOrange : inactiveTextColor;
                                    const fontWeight = isTabActive ? 'bold' : 'normal';
                                    const fontSize = isTabActive ? 15 : 15;

                                    return <TouchableOpacity
                                        style={{ flex: 1, backgroundColor: Colors.white }}
                                        key={name}
                                        onPress={() => onPressHandler(page)}>
                                        <View style={{
                                            flex: 1,
                                            alignItems: 'center',
                                            justifyContent: 'center',
                                            paddingBottom: 10,
                                        }}>
                                            <Text style={[{ color: textColor, fontWeight, fontSize: fontSize }, textStyle,]}>
                                                {name}
                                            </Text>
                                            {isTabActive ?
                                                <View style={{ width: 60 * unitWidth, height: 3 * unitWidth, backgroundColor: Colors.colorOrange, borderRadius: 15, position: 'absolute', bottom: 0 }} /> : null}
                                        </View>
                                    </TouchableOpacity>;
                                }} />}>
                            <Detail ref='screen1' tabLabel='详情' getHeight={(height) => {
                                this.setState({
                                    height: height,
                                    htmlHeight: height
                                })
                            }} refreshSuccess={() => {
                                this.setState({
                                    refreshing: false,
                                })
                            }}
                                content={this.state.goodsInfo.content} />
                            <MoreGoods ref='screen2' tabLabel='更多商品' getHeight={(height) => {
                                this.setState({ height: height })
                            }} refreshSuccess={() => {
                                this.setState({
                                    refreshing: false,
                                })
                            }} merchid={this.state.goodsInfo.merchid} navigation={this.props.navigation} />
                        </ScrollableTabView>
                    </View>
                </ScrollView>
                <View style={{
                    height: 50 * unitWidth, width: width, flexDirection: 'row', alignItems: 'center', justifyContent: 'center',
                    backgroundColor: Colors.white, position: 'absolute', bottom: 0
                }}>
                    <SubmitButton4 text='加入购物车' onPress={() => { this.add(this.id, 1) }} />
                    <SubmitButton5 style={{ marginLeft: 50 * unitWidth }} text='立即购买'
                        onPress={() => {
                            // this.refs.BottomCountModal.showModal();
                            this.props.navigation.navigate('ConfirmOrder', { id: this.state.goodsInfo.id })
                        }} />
                </View>
                <BottomCountModal ref='BottomCountModal' item={this.state.goodsInfo} />
            </View>
        )
    }

    //添加购物车
    add(id, total) {
        let params = {
            id: id,
            total: total
        }
        postFetch(api_member_cart_add, params, {
            success: (response) => {
                show('添加成功');
            },
            fail: (response) => {
                show(response.result.message);
            }
        })
    }

    getCarouselView() {
        let views = []
        for (let i = 0, len = this.state.CarouselList.length; i < len; i++) {
            let item = this.state.CarouselList[i];
            views.push(
                <TouchableOpacity key={i} style={{
                    justifyContent: 'center',
                    alignItems: 'center',
                }} activeOpacity={0.8} onPress={() => {

                }}>
                    <Image
                        source={{ uri: item }}
                        style={{
                            width: width, height: 225 * unitWidth,
                        }}
                        resizeMode='contain' />
                </TouchableOpacity>
            )
        }
        return views;
    }

    //刷新
    onRefresh() {
        this.setState({
            refreshing: true,
        });
        this.page = 1;
        if (this.refs.screen1 && this.state.currentChoose == 0) {
            // this.refs.screen1.onRefresh();
            this.getData()
        }
        if (this.refs.screen2 && this.state.currentChoose == 1) {
            this.refs.screen2.onRefresh();
        }
    }

    //加载更多
    onLoadMore() {
        if (this.refs.screen1 && this.state.currentChoose == 0) {
            // this.refs.screen1.onLoadMore();
        }
        if (this.refs.screen2 && this.state.currentChoose == 1) {
            this.refs.screen2.onLoadMore();
        }
    }

    //获取
    getData() {
        let params = {
            id: this.id
        }
        postFetch(api_goods_detail, params, {
            success: (response) => {
                this.setState({
                    goodsInfo: response.result,
                    CarouselList: response.result.thumb_url,
                    shopInfo: response.result.shopdetail,
                    refreshing: false
                })
            },
            fail: (response) => {
                this.setState({
                    refreshing: false
                })
                show(response.result.message);
            }
        })
    }
}

class Detail extends Component {
    constructor(props) {
        super(props)
        this.state = {

        }
        this.height = 0
    }

    componentDidMount() {

    }

    componentWillUnmount() {

    }

    measure(height) {
        this.props.getHeight ? this.props.getHeight(height ? height : 500) : null
    }

    render() {
        return (
            <View ref='view' style={{ width: width, flex: 1 }}>
                <WebView
                    ref='WebView'
                    style={{}}
                    automaticallyAdjustContentInsets
                    decelerationRate='normal'
                    scalesPageToFit
                    javaScriptEnabled // 仅限Android平台。iOS平台JavaScript是默认开启的。
                    domStorageEnabled // 适用于安卓
                    scrollEnabled={false}
                    onLoad={(event) => {

                    }}
                    onMessage={(event) => {
                        try {
                            const action = JSON.parse(event.nativeEvent.data);
                            const { type, height } = action;
                            console.log('111111111111111111111        ' + height)
                            this.measure(height + 80)
                        } catch (error) {
                            console.log('ShowWebViewPage onMessage错误', error);
                        }
                    }}
                    source={{ html: CommonUtil.getHeightHtml(this.props.content) }}
                // source={{ html: CommonUtil.getHeightHtml(p) }}
                />
            </View>
        )
    }
}

class MoreGoods extends Component {
    constructor(props) {
        super(props)
        this.state = {
            refreshing: false,
            showFoot: 0,//显示上拉加载更多
            list: [],
        }
        this.page = 1;
    }

    componentDidMount() {
        this.getData();
    }

    componentWillUnmount() {

    }

    measure() {
        this.props.getHeight ? this.props.getHeight(((parseInt((this.state.list.length + 1) / 2)) * 230 + 50) * unitWidth) : null
    }

    render() {
        return (
            <View ref='view' style={{ width: width }}>
                <FlatList
                    ref='list'
                    showsVerticalScrollIndicator={false}
                    scrollEnabled={false}
                    style={{ alignSelf: 'stretch' }}
                    data={this.state.list}
                    numColumns={2}
                    ListEmptyComponent={() => <EmptyView />}
                    keyExtractor={(item, index) => {
                        return index + '';
                    }}
                    renderItem={this.getItem.bind(this)}
                    ListFooterComponent={<RefreshFooter showFoot={this.state.showFoot} />}
                />
            </View>
        )
    }

    getItem({ item, index }) {
        return (
            <View style={{ justifyContent: 'center', alignItems: 'center', width: width / 2, height: 230 * unitWidth }}>
                <TouchableOpacity style={{
                    width: 172 * unitWidth, height: 215 * unitWidth,
                    alignItems: 'center', backgroundColor: Colors.white, borderRadius: 7, paddingHorizontal: 2 * unitWidth
                }} activeOpacity={0.5} onPress={() => { this.props.navigation.replace('GoodsDetail', { id: item.id }) }}>
                    <Image source={{ uri: item.thumb }}
                        style={{ width: 168 * unitWidth, height: 120 * unitWidth }}
                        resizeMode='cover' />
                    <Text style={{ fontWeight: 'bold', color: Colors.black, fontSize: 16, marginVertical: 4 * unitWidth }}>{item.title}</Text>
                    <View style={{ paddingHorizontal: 7 * unitWidth, borderWidth: 0.5, borderColor: Colors.colorRed, borderRadius: 5, alignSelf: 'flex-start' }}>
                        <Text style={{ color: Colors.colorRed, fontSize: 10, }}>线下价格:￥{item.offlineprice}</Text>
                    </View>
                    <View style={{ alignSelf: 'flex-start', marginTop: 5 * unitWidth, flexDirection: 'row', alignItems: 'center', width: 172 * unitWidth }}>
                        <Text style={{ color: Colors.colorRed, fontSize: 17, }}>￥{item.marketprice}</Text>
                        <DeleteTextView text={'￥' + item.productprice} style={{ marginLeft: 3 * unitWidth }} />
                        <AddShoppingCartButton
                            style={{ position: 'absolute', right: 10 * unitWidth, }}
                            id={item.id} />
                    </View>
                </TouchableOpacity>
            </View>
        );
    }

    onRefresh() {
        this.setState({
            refreshing: true,
            bbsList: [],
        }, () => {
            this.page = 1;
            this.getData();
        });
    }

    onLoadMore() {
        console.log('onLoadMore:' + this.state.showFoot);
        //如果是正在加载中或没有更多数据了，则返回
        if (this.state.showFoot != 0) {
            return;
        }
        //底部显示正在加载更多数据
        this.page++;
        this.setState({
            showFoot: 2,
        })
        this.getData();
        //获取数据
    }

    //获取商品列表
    getData() {
        let params = {
            page: this.page,
            merchid: this.props.merchid
        }
        postFetch(api_goods_get_list, params, {
            success: (response) => {
                this.props.refreshSuccess ? this.props.refreshSuccess() : null;
                if (this.page == 1) {
                    this.setState({
                        list: response.result.list,
                        showFoot: 0,
                        refreshing: false,
                    }, () => {
                        this.measure();
                    })
                } else {
                    if (response.result.list && response.result.list.length > 0) {
                        this.setState({
                            list: this.state.list.concat(response.result.list),
                            showFoot: 0,
                            refreshing: false,
                        }, () => {
                            this.measure();
                        })
                    } else {
                        this.setState({
                            refreshing: false,
                            showFoot: 1
                        })
                    }
                }
            },
            fail: (response) => {
                this.props.refreshSuccess ? this.props.refreshSuccess() : null;
                show(response.result.message);
            }
        })
    }
}